<template>
  <div class="main">
    <el-card class="box-card">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="ruleForm.password"
            @keyup.enter.native="submitForm('ruleForm')"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >登录</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { checkLogin } from "@/api/index";
export default {
  data() {
    //rule 表单验证规则   value 表单得到的输入的值  callback 回调函数 不管成功失败都必须调用
    var checkPass = (rule, value, callback) => {
      if (value.charAt(0) != "1") {
        return callback(new Error("密码第1位必须为1"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur"
          },
          // { pattern: /^\S$/, message: "密码格式错误", trigger: "blur" },
          //密码自定义验证规则
          { validator: checkPass, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName]
        .validate()
        .then(async () => {
          let {
            data: { token, username }
          } = await checkLogin(this.ruleForm);
          this.$message.success("登录成功");
          window.localStorage.setItem("tokenLogin", token);
          this.$store.commit("setToken", token);
          this.$store.commit("setUsername", username);
          this.$router.push("/");
        })
        .catch(() => {
          this.$message.error("登录失败");
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style scoped>
/* 每个组件的样式只能在自己的组件内生性 */

.box-card {
  width: 500px;
  height: 200px;
  margin: 0 auto;
}
.main {
  padding: 300px 0;
}
</style>
